<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"he7009.gitee.io","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
<meta property="og:type" content="website">
<meta property="og:title" content="he7009">
<meta property="og:url" content="https://he7009.gitee.io/index.html">
<meta property="og:site_name" content="he7009">
<meta property="og:description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="he7009">
<meta property="article:tag" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx、分享">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://he7009.gitee.io/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>he7009</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="he7009" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">he7009</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">天行健，君子以自强不息</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tag fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2021/03/27/docker/docker-compose-chang-yong-ming-ling/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/03/27/docker/docker-compose-chang-yong-ming-ling/" class="post-title-link" itemprop="url">Docker-Compose 构建 lnmp 环境</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-03-27 18:25:10 / 修改时间：18:27:44" itemprop="dateCreated datePublished" datetime="2021-03-27T18:25:10+08:00">2021-03-27</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Docker/" itemprop="url" rel="index"><span itemprop="name">Docker</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="docker-compose-yml-文件部分命令说明"><a href="#docker-compose-yml-文件部分命令说明" class="headerlink" title="docker-compose.yml 文件部分命令说明"></a>docker-compose.yml 文件部分命令说明</h2><hr>
<table>
<thead>
<tr>
<th>build</th>
<th>指定 Dockerfile 所在文件夹路径</th>
</tr>
</thead>
<tbody><tr>
<td>container_name</td>
<td>指定容器名称</td>
</tr>
<tr>
<td>depends_on</td>
<td>指定多个服务之间的依赖关系，启动时会先启动被依赖服务</td>
</tr>
<tr>
<td>entrypoint</td>
<td>覆盖容器中默认的入口命令</td>
</tr>
<tr>
<td>environment</td>
<td>设置环境变量</td>
</tr>
<tr>
<td>image</td>
<td>指定为镜像名称或镜像ID，如果本地镜像不存在，Compose会尝试拉取这个镜像</td>
</tr>
<tr>
<td>networks</td>
<td>所加入的网络</td>
</tr>
<tr>
<td>ports</td>
<td>端口映射</td>
</tr>
<tr>
<td>volumes</td>
<td>数据卷路径映射</td>
</tr>
<tr>
<td>restart</td>
<td>设置重启策略</td>
</tr>
</tbody></table>
<h2 id="创建容器、查看容器"><a href="#创建容器、查看容器" class="headerlink" title="创建容器、查看容器"></a>创建容器、查看容器</h2><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 创建容器</span>
<span class="token comment"># 会尝试构建镜像、创建容器、启动容器</span>
docker-compose up -d

<span class="token comment"># 查看容器</span>
docker-compose <span class="token function">ps</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="停止、启动、重新构建镜像、查看输出"><a href="#停止、启动、重新构建镜像、查看输出" class="headerlink" title="停止、启动、重新构建镜像、查看输出"></a>停止、启动、重新构建镜像、查看输出</h2><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 停止容器</span>
<span class="token comment"># 指定容器则关闭指定容器</span>
<span class="token comment"># 不指定容器则关闭所有容器</span>
docker-compose stop 容器名称

<span class="token comment"># 启动容器</span>
<span class="token comment"># 指定容器则启动指定容器</span>
<span class="token comment"># 不指定容器则启动所有容器</span>
docker-compose start 容器名称

<span class="token comment"># 重新构建镜像</span>
<span class="token comment"># 指定镜像则构建指定镜像</span>
<span class="token comment"># 不指定镜像则构建所有镜像</span>
docker-compose build 容器名称

<span class="token comment"># 查看容器输出</span>
docker-compose logs 容器名称
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="搭建-lnmp-环境"><a href="#搭建-lnmp-环境" class="headerlink" title="搭建 lnmp 环境"></a>搭建 lnmp 环境</h2><hr>
<h3 id="文件目录结构"><a href="#文件目录结构" class="headerlink" title="文件目录结构"></a>文件目录结构</h3><pre class="line-numbers language-dockerfile" data-language="dockerfile"><code class="language-dockerfile">├── data
│   └── mysql
├── logs
│   ├── mysql
│   ├── nginx
│   ├── php56
│   └── php74
├── services
│   ├── mysql
│   │   ├── Dockerfile
│   │   └── conf
│   │       ├── conf.d
│   │       │   ├── docker.cnf
│   │       │   └── mysql.cnf
│   │       ├── my.cnf
│   │       └── my.cnf.fallback
│   ├── nginx
│   │   ├── Dockerfile
│   │   └── conf
│   │       ├── cert
│   │       │   ├── www.key
│   │       │   └── www.pem
│   │       ├── fastcgi.conf
│   │       ├── fastcgi_params
│   │       ├── koi-utf
│   │       ├── koi-win
│   │       ├── mime.types
│   │       ├── nginx.conf
│   │       ├── rewrite
│   │       │   └── www.rewrite
│   │       ├── scgi_params
│   │       ├── uwsgi_params
│   │       ├── vhost
│   │       │   └── www.conf
│   │       └── win-utf
│   ├── php56
│   │   ├── Dockerfile
│   │   └── etc
│   │       ├── php
│   │       │   ├── php.ini
│   │       │   ├── php.ini-development
│   │       │   └── php.ini-production
│   │       ├── php-fpm.conf
│   │       ├── php-fpm.conf.default
│   │       └── php-fpm.d
│   │           ├── docker.conf
│   │           ├── www.conf
│   │           └── zz-docker.conf
│   └── php74
│       ├── Dockerfile
│       ├── etc
│       │   ├── php
│       │   │   ├── php.ini
│       │   │   ├── php.ini-development
│       │   │   └── php.ini-production
│       │   ├── php-fpm.conf
│       │   ├── php-fpm.conf.default
│       │   └── php-fpm.d
│       │       ├── docker.conf
│       │       ├── www.conf
│       │       └── zz-docker.conf
│       └── install-php-extensions
└── www
│   └── index.php
├── docker-compose.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="docker-compose-yml"><a href="#docker-compose-yml" class="headerlink" title="docker-compose.yml"></a>docker-compose.yml</h3><pre class="line-numbers language-yaml" data-language="yaml"><code class="language-yaml"><span class="token key atrule">version</span><span class="token punctuation">:</span> <span class="token string">"3"</span>
<span class="token key atrule">services</span><span class="token punctuation">:</span>
  <span class="token key atrule">nginx</span><span class="token punctuation">:</span>
    <span class="token key atrule">build</span><span class="token punctuation">:</span>
      <span class="token key atrule">context</span><span class="token punctuation">:</span> ./services/nginx
    <span class="token key atrule">container_name</span><span class="token punctuation">:</span> nginx
    <span class="token key atrule">ports</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token datetime number">80:80</span>
      <span class="token punctuation">-</span> 443<span class="token punctuation">:</span><span class="token number">443</span>
    <span class="token key atrule">volumes</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> ./www<span class="token punctuation">:</span>/www
      <span class="token punctuation">-</span> ./services/nginx/conf<span class="token punctuation">:</span>/etc/nginx
      <span class="token punctuation">-</span> ./logs/nginx<span class="token punctuation">:</span>/var/log/nginx
    <span class="token key atrule">restart</span><span class="token punctuation">:</span> always
    <span class="token key atrule">depends_on</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> php56
      <span class="token punctuation">-</span> php74
    <span class="token key atrule">environment</span><span class="token punctuation">:</span>
      <span class="token key atrule">TZ</span><span class="token punctuation">:</span> <span class="token string">"Asia/Shanghai"</span>

  <span class="token key atrule">php56</span><span class="token punctuation">:</span>
    <span class="token key atrule">build</span><span class="token punctuation">:</span>
      <span class="token key atrule">context</span><span class="token punctuation">:</span> ./services/php56
    <span class="token key atrule">container_name</span><span class="token punctuation">:</span> php56
    <span class="token key atrule">volumes</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> ./www<span class="token punctuation">:</span>/www
      <span class="token punctuation">-</span> ./services/php56/etc/php/php.ini<span class="token punctuation">:</span>/usr/local/etc/php/php.ini
      <span class="token punctuation">-</span> ./services/php56/etc/php<span class="token punctuation">-</span>fpm.conf<span class="token punctuation">:</span>/usr/local/etc/php<span class="token punctuation">-</span>fpm.conf
      <span class="token punctuation">-</span> ./services/php56/etc/php<span class="token punctuation">-</span>fpm.d<span class="token punctuation">:</span>/usr/local/etc/php<span class="token punctuation">-</span>fpm.d
      <span class="token punctuation">-</span> ./logs/php56<span class="token punctuation">:</span>/var/log/php
    <span class="token key atrule">restart</span><span class="token punctuation">:</span> always
    <span class="token key atrule">depends_on</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> mysql57
    <span class="token key atrule">environment</span><span class="token punctuation">:</span>
      <span class="token key atrule">TZ</span><span class="token punctuation">:</span> <span class="token string">"Asia/Shanghai"</span>

  <span class="token key atrule">php74</span><span class="token punctuation">:</span>
    <span class="token key atrule">build</span><span class="token punctuation">:</span>
      <span class="token key atrule">context</span><span class="token punctuation">:</span> ./services/php74
    <span class="token key atrule">container_name</span><span class="token punctuation">:</span> php74
    <span class="token key atrule">volumes</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> ./www<span class="token punctuation">:</span>/www
      <span class="token punctuation">-</span> ./services/php74/etc/php/php.ini<span class="token punctuation">:</span>/usr/local/etc/php/php.ini
      <span class="token punctuation">-</span> ./services/php74/etc/php<span class="token punctuation">-</span>fpm.conf<span class="token punctuation">:</span>/usr/local/etc/php<span class="token punctuation">-</span>fpm.conf
      <span class="token punctuation">-</span> ./services/php74/etc/php<span class="token punctuation">-</span>fpm.d<span class="token punctuation">:</span>/usr/local/etc/php<span class="token punctuation">-</span>fpm.d
      <span class="token punctuation">-</span> ./logs/php74<span class="token punctuation">:</span>/var/log/php
    <span class="token key atrule">restart</span><span class="token punctuation">:</span> always
    <span class="token key atrule">depends_on</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> mysql57
    <span class="token key atrule">environment</span><span class="token punctuation">:</span>
      <span class="token key atrule">TZ</span><span class="token punctuation">:</span> <span class="token string">"Asia/Shanghai"</span>

  <span class="token key atrule">mysql57</span><span class="token punctuation">:</span>
    <span class="token key atrule">container_name</span><span class="token punctuation">:</span> mysql57
    <span class="token key atrule">build</span><span class="token punctuation">:</span>
      <span class="token key atrule">context</span><span class="token punctuation">:</span> ./services/mysql
      <span class="token key atrule">args</span><span class="token punctuation">:</span>
        <span class="token punctuation">-</span> MYSQL_VER=5.7
    <span class="token key atrule">ports</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> 3306<span class="token punctuation">:</span><span class="token number">3306</span>
    <span class="token key atrule">volumes</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> ./services/mysql/conf<span class="token punctuation">:</span>/etc/mysql
      <span class="token punctuation">-</span> ./data/mysql<span class="token punctuation">:</span>/var/lib/mysql
      <span class="token punctuation">-</span> ./logs/mysql<span class="token punctuation">:</span>/var/log/mysql
    <span class="token key atrule">environment</span><span class="token punctuation">:</span>
      <span class="token key atrule">MYSQL_ROOT_PASSWORD</span><span class="token punctuation">:</span> <span class="token number">123456</span>
    <span class="token key atrule">restart</span><span class="token punctuation">:</span> always
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="PHP5-6-Dockerfile"><a href="#PHP5-6-Dockerfile" class="headerlink" title="PHP5.6 Dockerfile"></a>PHP5.6 Dockerfile</h3><pre class="line-numbers language-dockerfile" data-language="dockerfile"><code class="language-dockerfile"># 基础镜像
FROM php:5.6-fpm-alpine

# 修改系统镜像源、安装依赖
RUN sed -i &quot;s&#x2F;dl-cdn.alpinelinux.org&#x2F;mirrors.aliyun.com&#x2F;g&quot; &#x2F;etc&#x2F;apk&#x2F;repositories \
  &amp;&amp; apk update \
  &amp;&amp; apk --no-cache add tzdata \
  &amp;&amp; cp &quot;&#x2F;usr&#x2F;share&#x2F;zoneinfo&#x2F;Asia&#x2F;Shanghai&quot; &#x2F;etc&#x2F;localtime \
  &amp;&amp; echo &quot;Asia&#x2F;Shanghai&quot; &gt; &#x2F;etc&#x2F;timezone \
  &amp;&amp; apk add --no-cache --virtual .build-deps autoconf g++ libtool make linux-headers bzip2-dev libzip-dev

# 扩展脚本-用于安装PHP扩展
ADD ADD https:&#x2F;&#x2F;github.com&#x2F;mlocati&#x2F;docker-php-extension-installer&#x2F;releases&#x2F;latest&#x2F;download&#x2F;install-php-extensions &#x2F;usr&#x2F;local&#x2F;bin&#x2F;

# 安装 PHP 扩展
RUN chmod +x &#x2F;usr&#x2F;local&#x2F;bin&#x2F;install-php-extensions &amp;&amp; sync &amp;&amp; \
    install-php-extensions rdkafka pcntl swoole redis bcmath bz2 gd \
    gettext imagick mcrypt memcached mongodb mysqli pcntl \
    pdo_mysql shmop soap sockets sysvmsg sysvsem sysvshm xdebug \
    xmlrpc zip mysql

# 安装 PHP 分词扩展
RUN mkdir &#x2F;tmp&#x2F;extensions
WORKDIR &#x2F;tmp&#x2F;extensions
RUN mkdir &#x2F;tmp&#x2F;scws \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-1.2.3.tar.bz2 \
    &amp;&amp; tar -xjf &#x2F;tmp&#x2F;extensions&#x2F;scws-1.2.3.tar.bz2 -C &#x2F;tmp&#x2F;scws --strip-components&#x3D;1 \
    &amp;&amp; cd &#x2F;tmp&#x2F;scws  \
    &amp;&amp; .&#x2F;configure --prefix&#x3D;&#x2F;usr&#x2F;local&#x2F;scws  \
    &amp;&amp; make &amp;&amp; make install  \
    &amp;&amp; ( cd phpext &amp;&amp; phpize &amp;&amp; .&#x2F;configure --with-scws&#x3D;&#x2F;usr&#x2F;local&#x2F;scws &amp;&amp; make &amp;&amp; make install ) \
    &amp;&amp; cd &#x2F;usr&#x2F;local&#x2F;scws&#x2F;etc \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-dict-chs-gbk.tar.bz2 \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-dict-chs-utf8.tar.bz2 \
    &amp;&amp; tar -xvjf scws-dict-chs-gbk.tar.bz2 \
    &amp;&amp; tar -xvjf scws-dict-chs-utf8.tar.bz2 \
    &amp;&amp; docker-php-ext-enable scws \
    &amp;&amp; rm -rf &#x2F;tmp&#x2F;*

ENV LD_PRELOAD &#x2F;usr&#x2F;lib&#x2F;preloadable_libiconv.so php<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="PHP7-4-Dockerfile"><a href="#PHP7-4-Dockerfile" class="headerlink" title="PHP7.4 Dockerfile"></a>PHP7.4 Dockerfile</h3><pre class="line-numbers language-dockerfile" data-language="dockerfile"><code class="language-dockerfile"># 基础镜像
FROM php:7.4-fpm-alpine

# 修改系统镜像源、安装依赖
RUN sed -i &quot;s&#x2F;dl-cdn.alpinelinux.org&#x2F;mirrors.aliyun.com&#x2F;g&quot; &#x2F;etc&#x2F;apk&#x2F;repositories \
  &amp;&amp; apk update \
  &amp;&amp; apk --no-cache add tzdata \
  &amp;&amp; cp &quot;&#x2F;usr&#x2F;share&#x2F;zoneinfo&#x2F;Asia&#x2F;Shanghai&quot; &#x2F;etc&#x2F;localtime \
  &amp;&amp; echo &quot;Asia&#x2F;Shanghai&quot; &gt; &#x2F;etc&#x2F;timezone \
  &amp;&amp; apk add --no-cache --virtual .build-deps autoconf g++ libtool make linux-headers bzip2-dev libzip-dev

# 扩展脚本-用于安装PHP扩展
ADD ADD https:&#x2F;&#x2F;github.com&#x2F;mlocati&#x2F;docker-php-extension-installer&#x2F;releases&#x2F;latest&#x2F;download&#x2F;install-php-extensions &#x2F;usr&#x2F;local&#x2F;bin&#x2F;

# 安装 PHP 扩展
RUN chmod +x &#x2F;usr&#x2F;local&#x2F;bin&#x2F;install-php-extensions &amp;&amp; sync &amp;&amp; \
    install-php-extensions rdkafka pcntl swoole redis bcmath bz2 gd \
    gettext imagick mcrypt memcached mongodb mysqli pcntl \
    pdo_mysql shmop soap sockets sysvmsg sysvsem sysvshm xdebug \
    xmlrpc zip

# 安装 PHP 分词扩展
RUN mkdir &#x2F;tmp&#x2F;extensions
WORKDIR &#x2F;tmp&#x2F;extensions
RUN mkdir &#x2F;tmp&#x2F;scws \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-1.2.3.tar.bz2 \
    &amp;&amp; tar -xjf &#x2F;tmp&#x2F;extensions&#x2F;scws-1.2.3.tar.bz2 -C &#x2F;tmp&#x2F;scws --strip-components&#x3D;1 \
    &amp;&amp; cd &#x2F;tmp&#x2F;scws  \
    &amp;&amp; .&#x2F;configure --prefix&#x3D;&#x2F;usr&#x2F;local&#x2F;scws  \
    &amp;&amp; make &amp;&amp; make install  \
    &amp;&amp; ( cd phpext &amp;&amp; phpize &amp;&amp; .&#x2F;configure --with-scws&#x3D;&#x2F;usr&#x2F;local&#x2F;scws &amp;&amp; make &amp;&amp; make install ) \
    &amp;&amp; cd &#x2F;usr&#x2F;local&#x2F;scws&#x2F;etc \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-dict-chs-gbk.tar.bz2 \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-dict-chs-utf8.tar.bz2 \
    &amp;&amp; tar -xvjf scws-dict-chs-gbk.tar.bz2 \
    &amp;&amp; tar -xvjf scws-dict-chs-utf8.tar.bz2 \
    &amp;&amp; docker-php-ext-enable scws \
    &amp;&amp; rm -rf &#x2F;tmp&#x2F;*

ENV LD_PRELOAD &#x2F;usr&#x2F;lib&#x2F;preloadable_libiconv.so php<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="Nginx-Dockerfile"><a href="#Nginx-Dockerfile" class="headerlink" title="Nginx Dockerfile"></a>Nginx Dockerfile</h3><pre class="line-numbers language-dockerfile" data-language="dockerfile"><code class="language-dockerfile"># 基础镜像
FROM nginx:alpine

# 修改系统镜像源、安装依赖
RUN sed -i &quot;s&#x2F;dl-cdn.alpinelinux.org&#x2F;mirrors.aliyun.com&#x2F;g&quot; &#x2F;etc&#x2F;apk&#x2F;repositories \
  &amp;&amp; apk --no-cache add tzdata \
  &amp;&amp; cp &quot;&#x2F;usr&#x2F;share&#x2F;zoneinfo&#x2F;Asia&#x2F;Shanghai&quot; &#x2F;etc&#x2F;localtime \
  &amp;&amp; echo &quot;Asia&#x2F;Shanghai&quot; &gt; &#x2F;etc&#x2F;timezone
  <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="Mysql-Dockerfile"><a href="#Mysql-Dockerfile" class="headerlink" title="Mysql Dockerfile"></a>Mysql Dockerfile</h3><pre class="line-numbers language-dockerfile" data-language="dockerfile"><code class="language-dockerfile"># mysql 版本变量
ARG MYSQL_VER

# 基础镜像
FROM mysql:$&#123;MYSQL_VER&#125;

# 设置时区为上海
ENV TZ&#x3D;Asia&#x2F;Shanghai
RUN ln -snf &#x2F;usr&#x2F;share&#x2F;zoneinfo&#x2F;$TZ &#x2F;etc&#x2F;localtime &amp;&amp; echo $TZ &gt; &#x2F;etc&#x2F;timezone

# Ubuntu软件源选择中国的服务器
RUN sed -i &#39;s&#x2F;archive.ubuntu.com&#x2F;mirrors.aliyun.com&#x2F;g&#39; &#x2F;etc&#x2F;apt&#x2F;sources.list

# 更新安装依赖包
RUN apt-get update &amp;&amp; apt-get install -y vim wget<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2021/03/27/docker/docker-container-chang-yong-ming-ling/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/03/27/docker/docker-container-chang-yong-ming-ling/" class="post-title-link" itemprop="url">Docker-Container 常用命令</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-03-27 18:25:10 / 修改时间：18:27:44" itemprop="dateCreated datePublished" datetime="2021-03-27T18:25:10+08:00">2021-03-27</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Docker/" itemprop="url" rel="index"><span itemprop="name">Docker</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="查看容器和复制文件"><a href="#查看容器和复制文件" class="headerlink" title="查看容器和复制文件"></a>查看容器和复制文件</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 查看正在运行的容器列表</span>
docker <span class="token function">ps</span> 

<span class="token comment"># 查看所有容器列表</span>
docker <span class="token function">ps</span> -a

<span class="token comment"># 查看容器详情</span>
docker inspect <span class="token punctuation">(</span>容器名称:容器标签<span class="token punctuation">)</span><span class="token operator">|</span>容器ID

<span class="token comment"># 查看容器端口映射</span>
docker port <span class="token punctuation">(</span>容器名称:容器标签<span class="token punctuation">)</span><span class="token operator">|</span>容器ID

<span class="token comment"># 容器和主机之间复制文件</span>
<span class="token comment"># 本地复制到容器</span>
docker <span class="token function">cp</span> 本地路径 容器名称｜容器ID:容器内存储路径
<span class="token comment"># 容器内复制到本地</span>
docker <span class="token function">cp</span> 容器名称｜容器ID:容器内存储路径 本地路径
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="创建容器、进入容器"><a href="#创建容器、进入容器" class="headerlink" title="创建容器、进入容器"></a>创建容器、进入容器</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 创建容器、启动容器、创建并启动、查看容器输出信息</span>

<span class="token comment"># 创建容器</span>

  docker create -it --name 容器别名 -p 本地端口:容器端口 -v 本地路径:容器路径 --link 链接到其他容器 镜像名称:镜像标签

  <span class="token comment"># -i: 保持标准输入打开</span>
  <span class="token comment"># -t: 分配伪终端</span>
  <span class="token comment"># --name: 设置容器别名，后面可以使用容器别名来操作容器</span>
  <span class="token comment"># -p: 端口映射</span>
  <span class="token comment"># -v: 文件系统映射</span>
  <span class="token comment"># --link: 链接其他容器</span>


<span class="token comment"># 启动容器</span>

  docker start 容器ID｜容器别名


<span class="token comment"># 创建并启动容器</span>

  docker run  <span class="token punctuation">..</span>.

  <span class="token comment"># 相当于先创建 docker create 后 docker start 启动</span>
  <span class="token comment"># 加 -d 以守护进程启动</span>


<span class="token comment"># 查看容器输出信息</span>

	docker logs 容器ID｜容器别名
  

<span class="token comment"># 进入容器</span>

	docker <span class="token builtin class-name">exec</span> -it 容器ID｜容器别名 执行命令
  
	<span class="token comment"># -i: 打开标准输入，接受用户输入命令</span>
  <span class="token comment"># -t: 分配伪终端</span>
  <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="停止容器、删除容器"><a href="#停止容器、删除容器" class="headerlink" title="停止容器、删除容器"></a>停止容器、删除容器</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 停止容器</span>
docker stop 容器ID｜容器别名

<span class="token comment"># 删除容器</span>
docker <span class="token function">rm</span> 容器别名｜容器ID<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>



      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2021/03/27/docker/docker-image-chang-yong-ming-ling/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/03/27/docker/docker-image-chang-yong-ming-ling/" class="post-title-link" itemprop="url">Docker-image 常用命令</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-03-27 18:25:10 / 修改时间：18:27:44" itemprop="dateCreated datePublished" datetime="2021-03-27T18:25:10+08:00">2021-03-27</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Docker/" itemprop="url" rel="index"><span itemprop="name">Docker</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="查看镜像列表"><a href="#查看镜像列表" class="headerlink" title="查看镜像列表"></a>查看镜像列表</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">docker images		或者		docker image list<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h2 id="image-创建"><a href="#image-创建" class="headerlink" title="image 创建"></a>image 创建</h2><hr>
<ol>
<li>docker pull 直接拉取 image</li>
<li>dockerfile 构建</li>
<li>基于已有容器创建</li>
<li>导入本地 image</li>
</ol>
<h3 id="docker-pull"><a href="#docker-pull" class="headerlink" title="docker pull"></a>docker pull</h3><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 命令格式</span>
docker <span class="token punctuation">[</span>image<span class="token punctuation">]</span> pull NAME <span class="token punctuation">[</span> :TAG<span class="token punctuation">]</span>

<span class="token comment"># NAME：镜像名称</span>
<span class="token comment"># TAG：镜像标签</span>
<span class="token comment"># 如果不显式指定TAG, 则默认会选择latest标签</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="dockerfile-构建"><a href="#dockerfile-构建" class="headerlink" title="dockerfile 构建"></a>dockerfile 构建</h3><p>部分指令：</p>
<table>
<thead>
<tr>
<th align="center">指令</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">FROM</td>
<td align="center">指定所创建镜像的基础镜像</td>
</tr>
<tr>
<td align="center">LABEL</td>
<td align="center">LABEL 指令可以为生成的镜像添加元数据标签信息</td>
</tr>
<tr>
<td align="center">ARG</td>
<td align="center">定义创建镜像过程中使用的变量，镜像创建成功后变量将不再存在</td>
</tr>
<tr>
<td align="center">ENV</td>
<td align="center">指定环境变量，可以被后续的 RUN 指令使用，在镜像启动的容器中也会存在</td>
</tr>
<tr>
<td align="center">ENTRYPOINT</td>
<td align="center">指定镜像的默认入口命令</td>
</tr>
<tr>
<td align="center">WORKDIR</td>
<td align="center">为后续的 RUN、CMD、ENTRYPOINT 指令配置工作目录</td>
</tr>
<tr>
<td align="center">RUN</td>
<td align="center">运行指定命令</td>
</tr>
<tr>
<td align="center">CMD</td>
<td align="center">容器启动后默认执行的命令</td>
</tr>
<tr>
<td align="center">ADD</td>
<td align="center">添加内容到镜像；支持本地文件的相对路径和绝对路径，也可以是URL</td>
</tr>
<tr>
<td align="center">COPY</td>
<td align="center">复制本地主机内容到镜像</td>
</tr>
<tr>
<td align="center">EXPOSE</td>
<td align="center">声明服务监听的端口；只是声明并没有做端口映射</td>
</tr>
</tbody></table>
<p>示例：</p>
<pre class="line-numbers language-dockerfile" data-language="dockerfile"><code class="language-dockerfile">FROM php:7.4-fpm-alpine

RUN sed -i &quot;s&#x2F;dl-cdn.alpinelinux.org&#x2F;mirrors.aliyun.com&#x2F;g&quot; &#x2F;etc&#x2F;apk&#x2F;repositories \
  &amp;&amp; apk update \
  &amp;&amp; apk --no-cache add tzdata \
  &amp;&amp; cp &quot;&#x2F;usr&#x2F;share&#x2F;zoneinfo&#x2F;Asia&#x2F;Shanghai&quot; &#x2F;etc&#x2F;localtime \
  &amp;&amp; echo &quot;Asia&#x2F;Shanghai&quot; &gt; &#x2F;etc&#x2F;timezone \
  &amp;&amp; apk add --no-cache --virtual .build-deps autoconf g++ libtool make linux-headers bzip2-dev libzip-dev

ADD .&#x2F;install-php-extensions &#x2F;usr&#x2F;local&#x2F;bin&#x2F;

RUN chmod +x &#x2F;usr&#x2F;local&#x2F;bin&#x2F;install-php-extensions &amp;&amp; sync &amp;&amp; \
    install-php-extensions rdkafka pcntl swoole redis bcmath bz2 gd \
    gettext imagick mcrypt memcached mongodb mysqli pcntl \
    pdo_mysql shmop soap sockets sysvmsg sysvsem sysvshm xdebug \
    xmlrpc zip

RUN mkdir &#x2F;tmp&#x2F;extensions

WORKDIR &#x2F;tmp&#x2F;extensions

RUN mkdir &#x2F;tmp&#x2F;scws \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-1.2.3.tar.bz2 \
    &amp;&amp; tar -xjf &#x2F;tmp&#x2F;extensions&#x2F;scws-1.2.3.tar.bz2 -C &#x2F;tmp&#x2F;scws --strip-components&#x3D;1 \
    &amp;&amp; cd &#x2F;tmp&#x2F;scws  \
    &amp;&amp; .&#x2F;configure --prefix&#x3D;&#x2F;usr&#x2F;local&#x2F;scws  \
    &amp;&amp; make &amp;&amp; make install  \
    &amp;&amp; ( cd phpext &amp;&amp; phpize &amp;&amp; .&#x2F;configure --with-scws&#x3D;&#x2F;usr&#x2F;local&#x2F;scws &amp;&amp; make &amp;&amp; make install ) \
    &amp;&amp; cd &#x2F;usr&#x2F;local&#x2F;scws&#x2F;etc \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-dict-chs-gbk.tar.bz2 \
    &amp;&amp; wget http:&#x2F;&#x2F;www.xunsearch.com&#x2F;scws&#x2F;down&#x2F;scws-dict-chs-utf8.tar.bz2 \
    &amp;&amp; tar -xvjf scws-dict-chs-gbk.tar.bz2 \
    &amp;&amp; tar -xvjf scws-dict-chs-utf8.tar.bz2 \
    &amp;&amp; docker-php-ext-enable scws \
    &amp;&amp; rm -rf &#x2F;tmp&#x2F;*

ENV LD_PRELOAD &#x2F;usr&#x2F;lib&#x2F;preloadable_libiconv.so php<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>docker build 镜像</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 命令格式</span>
docker build <span class="token punctuation">[</span>OPTIONS<span class="token punctuation">]</span> <span class="token environment constant">PATH</span> <span class="token punctuation">[</span> URL I -

<span class="token comment"># 主要 OPTIONS</span>
<span class="token comment"># -build-arg : 为 dockerfile 中的 arg 变量赋值</span>
<span class="token comment"># -f : 指定 dockerfile 名称</span>
<span class="token comment"># -t : 指定 image 标签</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="基于已有容器创建"><a href="#基于已有容器创建" class="headerlink" title="基于已有容器创建"></a>基于已有容器创建</h3><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 命令格式</span>
docker <span class="token punctuation">[</span>container<span class="token punctuation">]</span> commit <span class="token punctuation">[</span>OPTIONS<span class="token punctuation">]</span> CONTAINER <span class="token punctuation">[</span>REPOSITORY <span class="token punctuation">[</span>:TAG<span class="token punctuation">]</span><span class="token punctuation">]</span>

<span class="token comment"># 主要OPTIONS</span>
<span class="token comment"># -c: 作者信息</span>
<span class="token comment"># -m: 提交信息</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="导入本地-image"><a href="#导入本地-image" class="headerlink" title="导入本地 image"></a>导入本地 image</h3><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 导出镜像</span>
docker save -o 导出镜像名称 镜像名称<span class="token punctuation">[</span>:镜像标签<span class="token punctuation">]</span>

<span class="token comment"># 载入镜像</span>
docker load -i 本地镜像文件

<span class="token comment"># 或者</span>
docker load <span class="token operator">&lt;</span> 本地镜像文件 
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h2 id="image-删除"><a href="#image-删除" class="headerlink" title="image 删除"></a>image 删除</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 删除单个镜像</span>
docker rmi 镜像名称:镜像标签		或者		docker rmi 镜像ID

<span class="token comment"># 按条件筛选之后删除</span>
docker rmi <span class="token variable"><span class="token variable">`</span>docker images <span class="token operator">|</span> <span class="token function">grep</span> xxxxx <span class="token operator">|</span> <span class="token function">awk</span> <span class="token string">'&#123;print <span class="token variable">$3</span>&#125;'</span><span class="token variable">`</span></span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>



      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2021/03/11/mysql/mysql-pei-zhi-qi-dong-xi-tong-bian-liang/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/03/11/mysql/mysql-pei-zhi-qi-dong-xi-tong-bian-liang/" class="post-title-link" itemprop="url">Mysql 配置、启动、系统变量</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-11 16:23:10" itemprop="dateCreated datePublished" datetime="2021-03-11T16:23:10+08:00">2021-03-11</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-03-13 16:27:25" itemprop="dateModified" datetime="2021-03-13T16:27:25+08:00">2021-03-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Mysql/" itemprop="url" rel="index"><span itemprop="name">Mysql</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="命令行中配置选项"><a href="#命令行中配置选项" class="headerlink" title="命令行中配置选项"></a>命令行中配置选项</h2><hr>
<p>命令行中配置选项分为长形式和短形式方式。例如：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment"># 配置默认的存储引擎-长形式</span>
mysql<span class="token operator">></span> mysqld <span class="token comment">--default-storage-engine=MyISAM</span>

<span class="token comment"># 链接数据库-短形式</span>
mysql<span class="token operator">></span> mysql <span class="token operator">-</span>h127<span class="token punctuation">.</span><span class="token number">0.0</span><span class="token number">.1</span> <span class="token operator">-</span>uroot <span class="token operator">-</span>p<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="长形式"><a href="#长形式" class="headerlink" title="长形式"></a>长形式</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token comment">--启动选项1[=值1] --启动选项2[=值2] ... --启动选项n[=值n]</span>

<span class="token comment"># 例如：</span>
mysql<span class="token operator">></span> mysqld <span class="token comment">--default-storage-engine=MyISAM</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<ol>
<li>选项名前加上<code>--</code>前缀</li>
<li>如果选项名是由多个单词构成的，它们之间可以由短划线<code>-</code>连接起来，也可以使用下划线<code>_</code>连接起来</li>
<li>选项名、=、选项值之间不可以有空白字符</li>
</ol>
<h3 id="短形式"><a href="#短形式" class="headerlink" title="短形式"></a>短形式</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token operator">-</span>启动选项<span class="token number">1</span><span class="token punctuation">[</span>空格<span class="token punctuation">]</span><span class="token punctuation">[</span>值<span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">-</span>启动选项<span class="token number">2</span><span class="token punctuation">[</span>空格<span class="token punctuation">]</span><span class="token punctuation">[</span>值<span class="token number">2</span><span class="token punctuation">]</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token operator">-</span>启动选项n<span class="token punctuation">[</span>空格<span class="token punctuation">]</span><span class="token punctuation">[</span>值n<span class="token punctuation">]</span>

<span class="token comment"># 例如：</span>
mysql<span class="token operator">></span> mysql <span class="token operator">-</span>h127<span class="token punctuation">.</span><span class="token number">0.0</span><span class="token number">.1</span> <span class="token operator">-</span>uroot <span class="token operator">-</span>p<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<ol>
<li>短形式的选项名只有一个字母，选项名前只加一个短划线<code>-</code>前缀</li>
<li>选项名和选项值之间可以没有间隙，或者用空白字符隔开</li>
<li><code>-p</code>选项有些特殊，<code>-p</code>和密码值之间不能有空白字符</li>
</ol>
<h2 id="配置文件中配置选项"><a href="#配置文件中配置选项" class="headerlink" title="配置文件中配置选项"></a>配置文件中配置选项</h2><hr>
<h3 id="配置选项"><a href="#配置选项" class="headerlink" title="配置选项"></a>配置选项</h3><p>与在命令行中指定启动选项不同的是，配置文件中的启动选项被划分为若干个组，每个组有一个组名，用中括号<code>[]</code>扩起来，像这样：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token punctuation">[</span>server<span class="token punctuation">]</span>
option1     					<span class="token comment">#这是option1，该选项不需要选项值</span>
option2 <span class="token operator">=</span> value2      <span class="token comment">#这是option2，该选项需要选项值</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>

<span class="token punctuation">[</span>mysqld<span class="token punctuation">]</span>
<span class="token punctuation">(</span>具体的启动选项<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span>

<span class="token punctuation">[</span>mysqld_safe<span class="token punctuation">]</span>
<span class="token punctuation">(</span>具体的启动选项<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span>

<span class="token punctuation">[</span>client<span class="token punctuation">]</span>
<span class="token punctuation">(</span>具体的启动选项<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span>

<span class="token punctuation">[</span>mysql<span class="token punctuation">]</span>
<span class="token punctuation">(</span>具体的启动选项<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span>

<span class="token punctuation">[</span>mysqladmin<span class="token punctuation">]</span>
<span class="token punctuation">(</span>具体的启动选项<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ol>
<li>配置文件中只能使用长形式的选项</li>
<li>定的启动选项不允许加<code>--</code>前缀，并且每行只指定一个选项</li>
<li><code>=</code>周围可以有空白字符</li>
<li>使用<code>#</code>来添加注释，从<code>#</code>出现直到行尾的内容都属于注释内容，读取配置文件时会忽略这些注释内容</li>
</ol>
<h3 id="加载配置选项"><a href="#加载配置选项" class="headerlink" title="加载配置选项"></a>加载配置选项</h3><p>配置文件中不同的选项组是给不同的启动命令使用的，如果选项组名称与程序名称相同，则组中的选项将专门应用于该程序。有两个选项组比较特别：</p>
<ul>
<li><p><code>[server]</code>组下边的启动选项将作用于所有的服务器程序。</p>
</li>
<li><p><code>[client]</code>组下边的启动选项将作用于所有的客户端程序。</p>
</li>
</ul>
<p>需要注意的一点是，<code>mysqld_safe</code>和<code>mysql.server</code>这两个程序在启动时都会读取<code>[mysqld]</code>选项组中的内容。读取如下：</p>
<table>
<thead>
<tr>
<th>启动命令</th>
<th>类别</th>
<th>能读取的组</th>
</tr>
</thead>
<tbody><tr>
<td>mysqld</td>
<td>启动服务器</td>
<td><code>[mysqld]</code>、<code>[server]</code></td>
</tr>
<tr>
<td>mysqld_safe</td>
<td>启动服务器</td>
<td><code>[mysqld]</code>、<code>[server]</code>、<code>[mysqld_safe]</code></td>
</tr>
<tr>
<td>mysql.server</td>
<td>启动服务器</td>
<td><code>[mysqld]</code>、<code>[server]</code>、<code>[mysqld_safe]</code></td>
</tr>
<tr>
<td>mysql</td>
<td>启动客户端</td>
<td><code>[mysql]</code>、<code>[client]</code></td>
</tr>
<tr>
<td>mysqladmin</td>
<td>启动客户端</td>
<td><code>[mysqladmin]</code>、<code>[client]</code></td>
</tr>
<tr>
<td>mysqldump</td>
<td>启动客户端</td>
<td><code>[mysqldump]</code>、<code>[client]</code></td>
</tr>
</tbody></table>
<h2 id="系统变量"><a href="#系统变量" class="headerlink" title="系统变量"></a>系统变量</h2><hr>
<h3 id="系统变量作用范围"><a href="#系统变量作用范围" class="headerlink" title="系统变量作用范围"></a>系统变量作用范围</h3><ul>
<li><p><code>GLOBAL</code>：全局变量，影响服务器的整体操作。</p>
</li>
<li><p><code>SESSION</code>：会话变量，影响某个客户端连接的操作。（注：<code>SESSION</code>有个别名叫<code>LOCAL</code>）</p>
</li>
</ul>
<h3 id="查看系统变量"><a href="#查看系统变量" class="headerlink" title="查看系统变量"></a>查看系统变量</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">SHOW</span> <span class="token punctuation">[</span><span class="token keyword">GLOBAL</span><span class="token operator">|</span><span class="token keyword">SESSION</span><span class="token punctuation">]</span> VARIABLES <span class="token punctuation">[</span><span class="token operator">LIKE</span> 匹配的模式<span class="token punctuation">]</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h3 id="设置系统变量"><a href="#设置系统变量" class="headerlink" title="设置系统变量"></a>设置系统变量</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SET</span> <span class="token punctuation">[</span><span class="token keyword">GLOBAL</span><span class="token operator">|</span><span class="token keyword">SESSION</span><span class="token punctuation">]</span> 系统变量名 <span class="token operator">=</span> 值<span class="token punctuation">;</span>
<span class="token comment"># 或者</span>
<span class="token keyword">SET</span> <span class="token punctuation">[</span>@@<span class="token punctuation">(</span><span class="token keyword">GLOBAL</span><span class="token operator">|</span><span class="token keyword">SESSION</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token punctuation">]</span>var_name <span class="token operator">=</span> XXX<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>


<h2 id="状态变量"><a href="#状态变量" class="headerlink" title="状态变量"></a>状态变量</h2><hr>
<p>为了让我们更好的了解服务器程序的运行情况，<code>MySQL</code>服务器程序中维护了好多关于程序运行状态的变量，它们被称为<code>状态变量</code>。比方说<code>Threads_connected</code>表示当前有多少客户端与服务器建立了连接。</p>
<p>查看状态变量：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">SHOW</span> <span class="token punctuation">[</span><span class="token keyword">GLOBAL</span><span class="token operator">|</span><span class="token keyword">SESSION</span><span class="token punctuation">]</span> <span class="token keyword">STATUS</span> <span class="token punctuation">[</span><span class="token operator">LIKE</span> 匹配的模式<span class="token punctuation">]</span><span class="token punctuation">;</span>

<span class="token comment"># 例如：</span>
<span class="token keyword">SHOW</span> <span class="token keyword">STATUS</span> <span class="token operator">LIKE</span> <span class="token string">'thread%'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2021/03/05/mysql/mysql-yong-hu-quan-xian-guan-li/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/03/05/mysql/mysql-yong-hu-quan-xian-guan-li/" class="post-title-link" itemprop="url">Mysql 用户、权限管理</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-05 17:54:10" itemprop="dateCreated datePublished" datetime="2021-03-05T17:54:10+08:00">2021-03-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-03-07 13:54:51" itemprop="dateModified" datetime="2021-03-07T13:54:51+08:00">2021-03-07</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Mysql/" itemprop="url" rel="index"><span itemprop="name">Mysql</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="创建用户"><a href="#创建用户" class="headerlink" title="创建用户"></a>创建用户</h2><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">create</span> <span class="token keyword">user</span> <span class="token string">'用户名'</span><span class="token variable">@'主机地址'</span> identified <span class="token keyword">by</span> <span class="token string">'密码'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h2 id="修改用户密码"><a href="#修改用户密码" class="headerlink" title="修改用户密码"></a>修改用户密码</h2><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">alter</span> <span class="token keyword">user</span> <span class="token string">'用户名'</span><span class="token variable">@'主机地址'</span> identified <span class="token keyword">by</span> <span class="token string">'密码'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h2 id="修改用户名"><a href="#修改用户名" class="headerlink" title="修改用户名"></a>修改用户名</h2><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">rename</span> <span class="token keyword">user</span> <span class="token string">'旧用户'</span><span class="token variable">@'主机名'</span> <span class="token keyword">TO</span> <span class="token string">'新用户名'</span><span class="token variable">@'主机名'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h2 id="用户权限"><a href="#用户权限" class="headerlink" title="用户权限"></a>用户权限</h2><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">grant</span> 权限列表 <span class="token keyword">on</span> 库<span class="token punctuation">.</span>表 <span class="token keyword">to</span> <span class="token string">'用户名'</span><span class="token variable">@'主机地址'</span><span class="token punctuation">;</span>
mysql<span class="token operator">></span> flush <span class="token keyword">privileges</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<table>
<thead>
<tr>
<th align="center">权限</th>
<th align="center">作用范围</th>
<th align="center">作用</th>
</tr>
</thead>
<tbody><tr>
<td align="center">all</td>
<td align="center">服务</td>
<td align="center">所有权限</td>
</tr>
<tr>
<td align="center">select</td>
<td align="center">表、列</td>
<td align="center">选择行</td>
</tr>
<tr>
<td align="center">insert</td>
<td align="center">表、列</td>
<td align="center">插入行</td>
</tr>
<tr>
<td align="center">update</td>
<td align="center">表、列</td>
<td align="center">更新行</td>
</tr>
<tr>
<td align="center">delete</td>
<td align="center">表</td>
<td align="center">删除行</td>
</tr>
<tr>
<td align="center">create</td>
<td align="center">数据库、表、索引</td>
<td align="center">创建</td>
</tr>
<tr>
<td align="center">drop</td>
<td align="center">数据库、表、视图</td>
<td align="center">删除</td>
</tr>
<tr>
<td align="center">reload</td>
<td align="center">服务器</td>
<td align="center">允许使用flush语句</td>
</tr>
<tr>
<td align="center">shutdown</td>
<td align="center">服务器</td>
<td align="center">关闭服务</td>
</tr>
<tr>
<td align="center">process</td>
<td align="center">服务器</td>
<td align="center">查看线程信息</td>
</tr>
<tr>
<td align="center">file</td>
<td align="center">服务器</td>
<td align="center">文件操作</td>
</tr>
<tr>
<td align="center">grant option</td>
<td align="center">数据库、表、存储过程</td>
<td align="center">授权</td>
</tr>
<tr>
<td align="center">references</td>
<td align="center">数据库、表</td>
<td align="center">外键约束的父表</td>
</tr>
<tr>
<td align="center">index</td>
<td align="center">表</td>
<td align="center">创建/删除索引</td>
</tr>
<tr>
<td align="center">alter</td>
<td align="center">表</td>
<td align="center">修改表结构</td>
</tr>
<tr>
<td align="center">show databases</td>
<td align="center">服务器</td>
<td align="center">查看数据库名称</td>
</tr>
<tr>
<td align="center">super</td>
<td align="center">服务器</td>
<td align="center">超级权限</td>
</tr>
<tr>
<td align="center">create temporary tables</td>
<td align="center">表</td>
<td align="center">创建临时表</td>
</tr>
<tr>
<td align="center">lock tables</td>
<td align="center">数据库</td>
<td align="center">锁表</td>
</tr>
<tr>
<td align="center">execute</td>
<td align="center">存储过程</td>
<td align="center">执行</td>
</tr>
<tr>
<td align="center">replication client</td>
<td align="center">服务器</td>
<td align="center">允许查看主/从/二进制日志状态</td>
</tr>
<tr>
<td align="center">replication slave</td>
<td align="center">服务器</td>
<td align="center">主从复制</td>
</tr>
<tr>
<td align="center">create view</td>
<td align="center">视图</td>
<td align="center">创建视图</td>
</tr>
<tr>
<td align="center">show view</td>
<td align="center">视图</td>
<td align="center">查看视图</td>
</tr>
<tr>
<td align="center">create routine</td>
<td align="center">存储过程</td>
<td align="center">创建存储过程</td>
</tr>
<tr>
<td align="center">alter routine</td>
<td align="center">存储过程</td>
<td align="center">修改/删除存储过程</td>
</tr>
<tr>
<td align="center">create user</td>
<td align="center">服务器</td>
<td align="center">创建用户</td>
</tr>
<tr>
<td align="center">event</td>
<td align="center">数据库</td>
<td align="center">创建/更改/删除/查看事件</td>
</tr>
<tr>
<td align="center">trigger</td>
<td align="center">表</td>
<td align="center">触发器</td>
</tr>
<tr>
<td align="center">create tablespace</td>
<td align="center">服务器</td>
<td align="center">创建/更改/删除表空间/日志文件</td>
</tr>
<tr>
<td align="center">proxy</td>
<td align="center">服务器</td>
<td align="center">代理成为其它用户</td>
</tr>
<tr>
<td align="center">usage</td>
<td align="center">服务器</td>
<td align="center">没有权限</td>
</tr>
</tbody></table>
<h2 id="删除用户"><a href="#删除用户" class="headerlink" title="删除用户"></a>删除用户</h2><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">mysql<span class="token operator">></span> <span class="token keyword">drop</span> <span class="token keyword">user</span> <span class="token string">"用户名"</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>




      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2021/03/04/linux/linux-ssh-mian-mi-deng-lu-pei-zhi/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2021/03/04/linux/linux-ssh-mian-mi-deng-lu-pei-zhi/" class="post-title-link" itemprop="url">Linux ssh免密登录配置</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-04 23:14:10" itemprop="dateCreated datePublished" datetime="2021-03-04T23:14:10+08:00">2021-03-04</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-03-05 18:05:20" itemprop="dateModified" datetime="2021-03-05T18:05:20+08:00">2021-03-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Linux/" itemprop="url" rel="index"><span itemprop="name">Linux</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="Linux-ssh免密登录配置"><a href="#Linux-ssh免密登录配置" class="headerlink" title="Linux ssh免密登录配置"></a>Linux ssh免密登录配置</h1><h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><hr>
<p>ssh 通过加密解密的方式进行权限的验证；因此需要在客户端生成一对密钥；同时复制公钥到服务端。</p>
<h2 id="生成密钥对"><a href="#生成密钥对" class="headerlink" title="生成密钥对"></a>生成密钥对</h2><hr>
<p>客户端终端执行一下命令</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 一顿操作</span>
ssh-keygen<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>~/.ssh 目录会生成一对密钥；id_rsa (私钥) 、id_rsa.pub（公钥）</p>
<h2 id="复制公钥到远程服务器"><a href="#复制公钥到远程服务器" class="headerlink" title="复制公钥到远程服务器"></a>复制公钥到远程服务器</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#方法一：ssh-copy-id</span>
<span class="token comment"># ssh-copy-id - 将你的公共密钥填充到一个远程机器上的authorized_keys文件中</span>
<span class="token comment"># 远程服务器 ～/.ssh/authorized_keys 文件</span>

ssh-copy-id <span class="token operator">&lt;</span>Users<span class="token operator">></span>@host

<span class="token comment"># 会提示输入远程服务器密码</span>

<span class="token comment">#方法二：直接复制内容</span>
<span class="token comment"># 客户端查看公钥内容</span>
<span class="token function">cat</span> ~/.ssh/id_rsa.pub

<span class="token comment"># 复制内容</span>

<span class="token comment"># 粘贴到远程服务器 authorized_keys 文件</span>

<span class="token function">vim</span> ～/.ssh/authorized_key

<span class="token comment"># 粘贴后保存</span>
:wq<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="连接验证"><a href="#连接验证" class="headerlink" title="连接验证"></a>连接验证</h2><hr>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># ssh 连接远程服务器</span>
<span class="token function">ssh</span> <span class="token operator">&lt;</span>Users<span class="token operator">></span>@host<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h2 id="SSH-HostName-方式链接配置"><a href="#SSH-HostName-方式链接配置" class="headerlink" title="SSH HostName 方式链接配置"></a>SSH HostName 方式链接配置</h2><hr>
<p>配置远程服务器地址和用户名，从而避免每次输入用户名和远程服务器地址</p>
<pre class="line-numbers language-yaml" data-language="yaml"><code class="language-yaml"><span class="token comment"># 编辑 ~/.ssh/config 文件 添加配置</span>

Host &lt;以后使用的hostname<span class="token punctuation">></span>
        HostName 远程服务器地址
        User 用户名


<span class="token comment"># 示例配置</span>
Host aliyun
		HostName 48.44.102.134
        User root     
<span class="token comment"># 登录</span>
ssh aliyun<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2020/12/10/go/go-error-chu-li/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/12/10/go/go-error-chu-li/" class="post-title-link" itemprop="url">GO Error 处理</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-12-10 15:13:10" itemprop="dateCreated datePublished" datetime="2020-12-10T15:13:10+08:00">2020-12-10</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-02-27 00:11:03" itemprop="dateModified" datetime="2021-02-27T00:11:03+08:00">2021-02-27</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Go/" itemprop="url" rel="index"><span itemprop="name">Go</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="关于错误处理的几点理解"><a href="#关于错误处理的几点理解" class="headerlink" title="关于错误处理的几点理解"></a>关于错误处理的几点理解</h2><hr>
<ol>
<li>错误只应该被处理一次，写日志、降级、返回错误等都算作对错误的处理。写了日志、做了降级就不应该继续返回错误；如果返回错误，则不做其他处理。</li>
<li>错误应该包含错误信息和堆栈信息，以便于后续的错误查找和调试。</li>
<li>项目中应该尽量简洁明了的进行错误的判断处理。</li>
</ol>
<h2 id="早期的错误处理"><a href="#早期的错误处理" class="headerlink" title="早期的错误处理"></a>早期的错误处理</h2><hr>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> errors

<span class="token comment">//创建包含错误信息的错误</span>
<span class="token keyword">func</span> <span class="token function">New</span><span class="token punctuation">(</span>text <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token operator">&amp;</span>errorString<span class="token punctuation">&#123;</span>text<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">type</span> errorString <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	s <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现 Error 接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>e <span class="token operator">*</span>errorString<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> e<span class="token punctuation">.</span>s
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>只是简单的包含错误的信息，存在两个问题：</p>
<ul>
<li>上层无法添加错误信息</li>
<li>错误信息不包含堆栈信息；不利于调试和错误查找</li>
</ul>
<h2 id="GO-1-13-错误处理"><a href="#GO-1-13-错误处理" class="headerlink" title="GO 1.13 错误处理"></a>GO 1.13 错误处理</h2><hr>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//errors package</span>

<span class="token comment">//判断是否实现 interface &#123; Unwrap() error &#125; 接口，实现则调用返回根错误</span>
<span class="token keyword">func</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	u<span class="token punctuation">,</span> ok <span class="token operator">:=</span> err<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token keyword">interface</span> <span class="token punctuation">&#123;</span>
		<span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token boolean">nil</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> u<span class="token punctuation">.</span><span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//判断 err 错误是否 等于 target 错误，或者包含 target 错误</span>
<span class="token comment">//如果 err 和 target 是同一个，那么返回true</span>
<span class="token comment">//如果 err 是一个打包(wrap) 错误;并且 err 包含 target 错误 返回true</span>
<span class="token comment">//不等于也不包含则返回false</span>
<span class="token keyword">func</span> <span class="token function">Is</span><span class="token punctuation">(</span>err<span class="token punctuation">,</span> target <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//获取错误中包含的 具体错误，方法内部进行断言</span>
<span class="token keyword">func</span> <span class="token function">As</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> target <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//fmt package</span>

<span class="token comment">//打包根错误、添加错误信息；实现 interface &#123; Unwrap() error &#125; 接口来返回根错误</span>
<span class="token keyword">func</span> <span class="token function">Errorf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> a <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//wrapErro struct 包装 error</span>
<span class="token keyword">type</span> wrapError <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	msg <span class="token builtin">string</span>
	err <span class="token builtin">error</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现error接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>e <span class="token operator">*</span>wrapError<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> e<span class="token punctuation">.</span>msg
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现Unwrap接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>e <span class="token operator">*</span>wrapError<span class="token punctuation">)</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> e<span class="token punctuation">.</span>err
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>GO 1.13 可以通过fmt.Errorf 对错误信息进行wrap,进而添加错误信息;与此同时 errors package 中提供了对错误的Unwrap、 Is、As 方法,用以获取根错误信息和对错误的比较、判断等</p>
<p>增加了错误信息的wrap但是还是缺少堆栈信息的保存</p>
<h2 id="pkg-errors"><a href="#pkg-errors" class="headerlink" title="pkg/errors"></a>pkg/errors</h2><hr>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">//github.com/pkg/errors</span>

<span class="token comment">//包含堆栈信息的error</span>
<span class="token keyword">type</span> fundamental <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	msg <span class="token builtin">string</span>
	<span class="token operator">*</span>stack
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现 error 接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>f <span class="token operator">*</span>fundamental<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> f<span class="token punctuation">.</span>msg <span class="token punctuation">&#125;</span>
<span class="token comment">//重写format</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>f <span class="token operator">*</span>fundamental<span class="token punctuation">)</span> <span class="token function">Format</span><span class="token punctuation">(</span>s fmt<span class="token punctuation">.</span>State<span class="token punctuation">,</span> verb <span class="token builtin">rune</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">switch</span> verb <span class="token punctuation">&#123;</span>
	<span class="token keyword">case</span> <span class="token string">'v'</span><span class="token punctuation">:</span>
		<span class="token keyword">if</span> s<span class="token punctuation">.</span><span class="token function">Flag</span><span class="token punctuation">(</span><span class="token string">'+'</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			io<span class="token punctuation">.</span><span class="token function">WriteString</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> f<span class="token punctuation">.</span>msg<span class="token punctuation">)</span>
			f<span class="token punctuation">.</span>stack<span class="token punctuation">.</span><span class="token function">Format</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> verb<span class="token punctuation">)</span>
			<span class="token keyword">return</span>
		<span class="token punctuation">&#125;</span>
		<span class="token keyword">fallthrough</span>
	<span class="token keyword">case</span> <span class="token string">'s'</span><span class="token punctuation">:</span>
		io<span class="token punctuation">.</span><span class="token function">WriteString</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> f<span class="token punctuation">.</span>msg<span class="token punctuation">)</span>
	<span class="token keyword">case</span> <span class="token string">'q'</span><span class="token punctuation">:</span>
		fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">"%q"</span><span class="token punctuation">,</span> f<span class="token punctuation">.</span>msg<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>



<span class="token comment">// withStack struct 打包error,包含堆栈信息</span>
<span class="token keyword">type</span> withStack <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	<span class="token builtin">error</span>
	<span class="token operator">*</span>stack
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现Cause接口，返回根错误</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withStack<span class="token punctuation">)</span> <span class="token function">Cause</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span><span class="token builtin">error</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 实现Unwrap接口，返回根错误（用于兼容GO 1.13）</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withStack<span class="token punctuation">)</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span><span class="token builtin">error</span> <span class="token punctuation">&#125;</span>



<span class="token comment">// withMessage 打包 error,添加错误信息</span>
<span class="token keyword">type</span> withMessage <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	cause <span class="token builtin">error</span>
	msg   <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withMessage<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span>msg <span class="token operator">+</span> <span class="token string">": "</span> <span class="token operator">+</span> w<span class="token punctuation">.</span>cause<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">//实现Cause接口，返回根错误</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withMessage<span class="token punctuation">)</span> <span class="token function">Cause</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>  <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span>cause <span class="token punctuation">&#125;</span>
<span class="token comment">// 实现Unwrap接口，返回根错误（用于兼容GO 1.13）</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withMessage<span class="token punctuation">)</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span>cause <span class="token punctuation">&#125;</span>



<span class="token comment">//基于 fundamental 创建包含 错误信息 和 堆栈信息 的错误</span>
<span class="token keyword">func</span> <span class="token function">New</span><span class="token punctuation">(</span>message <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">Errorf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//打包（wrap）错误;添加 堆栈信息；</span>
<span class="token comment">//实现了interface &#123; Cause() error &#125; 接口</span>
<span class="token comment">//实现了interface &#123; Unwrap() error &#125; 接口兼容 GO 1.13</span>
<span class="token keyword">func</span> <span class="token function">WithStack</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//打包（wrap）错误;添加 错误信息；</span>
<span class="token comment">//实现了interface &#123; Cause() error &#125; 接口</span>
<span class="token comment">//实现了interface &#123; Unwrap() error &#125; 接口兼容 GO 1.13</span>
<span class="token keyword">func</span> <span class="token function">WithMessage</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> message <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">WithMessagef</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//打包（wrap）错误;添加 错误信息 和 堆栈信息</span>
<span class="token comment">//实现了interface &#123; Cause() error &#125; 接口</span>
<span class="token comment">//实现了interface &#123; Unwrap() error &#125; 接口兼容 GO 1.13</span>
<span class="token keyword">func</span> <span class="token function">Wrap</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> message <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">Wrapf</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//判断是否实现 interface &#123; Cause() error &#125; 接口，实现则调用返回根错误；等同于 GO 1.13 的 Unwrap()</span>
<span class="token keyword">func</span> <span class="token function">Cause</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h2 id="使用建议"><a href="#使用建议" class="headerlink" title="使用建议"></a>使用建议</h2><hr>
<ol>
<li>综合使用 GO 1.13 和 pgk/errors；pkg/errors 打包处理的错误 GO 1.13 提供的 Unwrap、Is、As 同样可以使用</li>
<li>自己应用层的代码，出现错误；可以使用 pkg/errors 的包，创建一个包含错误信息 和 堆栈信息的错误进行返回</li>
<li>对于别人返回的错误，如果是底层的未包含堆栈信息的错误可以使用 wrap 打包错误，添加错误信息 和 堆栈信息</li>
<li>对于别人返回的错误，如果是已经打包，包含 堆栈信息 的错误则直接返回。</li>
</ol>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2020/12/08/go/go-time/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/12/08/go/go-time/" class="post-title-link" itemprop="url">GO - Time</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-12-08 23:02:10" itemprop="dateCreated datePublished" datetime="2020-12-08T23:02:10+08:00">2020-12-08</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-12-09 13:13:32" itemprop="dateModified" datetime="2020-12-09T13:13:32+08:00">2020-12-09</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Go/" itemprop="url" rel="index"><span itemprop="name">Go</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="Go-time"><a href="#Go-time" class="headerlink" title="Go-time"></a>Go-time</h1><h2 id="time-time"><a href="#time-time" class="headerlink" title="time-time"></a>time-time</h2><h2 id="time-Timer"><a href="#time-Timer" class="headerlink" title="time-Timer"></a>time-Timer</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">//暂停当前goroutine</span>
<span class="token keyword">func</span> <span class="token function">Sleep</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">)</span>

<span class="token comment">//定时器</span>
<span class="token keyword">type</span> Timer <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	C <span class="token operator">&lt;-</span><span class="token keyword">chan</span> Time
	r runtimeTimer
<span class="token punctuation">&#125;</span>
<span class="token comment">//暂停timer</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Timer<span class="token punctuation">)</span> <span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token comment">//暂停定时器，并且重新开始一个新的定时器</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Timer<span class="token punctuation">)</span> <span class="token function">Reset</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

    
<span class="token comment">//快速创建timer</span>
<span class="token keyword">func</span> <span class="token function">NewTimer</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">)</span> <span class="token operator">*</span>Timer <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">After</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">)</span> <span class="token operator">&lt;-</span><span class="token keyword">chan</span> Time <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">AfterFunc</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">,</span> f <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">*</span>Timer <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>


<span class="token comment">//开启协程，执行函数</span>
<span class="token keyword">func</span> <span class="token function">goFunc</span><span class="token punctuation">(</span>arg <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> seq <span class="token builtin">uintptr</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//定时器默认方法；发送当前时间到 channel</span>
<span class="token keyword">func</span> <span class="token function">sendTime</span><span class="token punctuation">(</span>c <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> seq <span class="token builtin">uintptr</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="time-Ticker"><a href="#time-Ticker" class="headerlink" title="time-Ticker"></a>time-Ticker</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//</span>
<span class="token keyword">type</span> Ticker <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	C <span class="token operator">&lt;-</span><span class="token keyword">chan</span> Time <span class="token comment">// The channel on which the ticks are delivered.</span>
	r runtimeTimer
<span class="token punctuation">&#125;</span>
<span class="token comment">//暂停ticker</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>Ticker<span class="token punctuation">)</span> <span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//快速创建ticker</span>
<span class="token keyword">func</span> <span class="token function">NewTicker</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">)</span> <span class="token operator">*</span>Ticker <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">Tick</span><span class="token punctuation">(</span>d Duration<span class="token punctuation">)</span> <span class="token operator">&lt;-</span><span class="token keyword">chan</span> Time <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2020/12/07/go/go-context-yuan-ma-jie-du/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/12/07/go/go-context-yuan-ma-jie-du/" class="post-title-link" itemprop="url">GO - Context 源码解读</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-12-07 23:13:10" itemprop="dateCreated datePublished" datetime="2020-12-07T23:13:10+08:00">2020-12-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-12-10 15:33:29" itemprop="dateModified" datetime="2020-12-10T15:33:29+08:00">2020-12-10</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Go/" itemprop="url" rel="index"><span itemprop="name">Go</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="GO-Context-源码解读"><a href="#GO-Context-源码解读" class="headerlink" title="GO - Context 源码解读"></a>GO - Context 源码解读</h1><h2 id="核心接口"><a href="#核心接口" class="headerlink" title="核心接口"></a>核心接口</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">//Context interface</span>
<span class="token keyword">type</span> Context <span class="token keyword">interface</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//返回过期时间</span>
	<span class="token function">Deadline</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>deadline time<span class="token punctuation">.</span>Time<span class="token punctuation">,</span> ok <span class="token builtin">bool</span><span class="token punctuation">)</span>
    <span class="token comment">//返回 channel。用来判断 goroutine 是否结束</span>
	<span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;-</span><span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
    <span class="token comment">//goroutine 结束错误提示</span>
	<span class="token function">Err</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>
    <span class="token comment">//根据Key返回value</span>
	<span class="token function">Value</span><span class="token punctuation">(</span>key <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// sentinel Error; 主动 cancel</span>
<span class="token keyword">var</span> Canceled <span class="token operator">=</span> errors<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"context canceled"</span><span class="token punctuation">)</span>
<span class="token comment">// sentinel Error - Deadline Error</span>
<span class="token keyword">var</span> DeadlineExceeded <span class="token builtin">error</span> <span class="token operator">=</span> deadlineExceededError<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">type</span> deadlineExceededError <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>deadlineExceededError<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span>   <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> <span class="token string">"context deadline exceeded"</span> <span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>deadlineExceededError<span class="token punctuation">)</span> <span class="token function">Timeout</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>   <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> <span class="token boolean">true</span> <span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>deadlineExceededError<span class="token punctuation">)</span> <span class="token function">Temporary</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> <span class="token boolean">true</span> <span class="token punctuation">&#125;</span>

<span class="token comment">//空 Context; 实现 Context interface </span>
<span class="token keyword">type</span> emptyCtx <span class="token builtin">int</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span><span class="token operator">*</span>emptyCtx<span class="token punctuation">)</span> <span class="token function">Deadline</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>deadline time<span class="token punctuation">.</span>Time<span class="token punctuation">,</span> ok <span class="token builtin">bool</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span><span class="token operator">*</span>emptyCtx<span class="token punctuation">)</span> <span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;-</span><span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span><span class="token operator">*</span>emptyCtx<span class="token punctuation">)</span> <span class="token function">Err</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span><span class="token operator">*</span>emptyCtx<span class="token punctuation">)</span> <span class="token function">Value</span><span class="token punctuation">(</span>key <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">var</span> <span class="token punctuation">(</span>
	background <span class="token operator">=</span> <span class="token function">new</span><span class="token punctuation">(</span>emptyCtx<span class="token punctuation">)</span>
	todo       <span class="token operator">=</span> <span class="token function">new</span><span class="token punctuation">(</span>emptyCtx<span class="token punctuation">)</span>
<span class="token punctuation">)</span>
<span class="token comment">//返回 emptycxt</span>
<span class="token keyword">func</span> <span class="token function">Background</span><span class="token punctuation">(</span><span class="token punctuation">)</span> Context <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> background
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">TODO</span><span class="token punctuation">(</span><span class="token punctuation">)</span> Context <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> todo
<span class="token punctuation">&#125;</span>

<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="cancelCtx-Struct-实现取消功能"><a href="#cancelCtx-Struct-实现取消功能" class="headerlink" title="cancelCtx Struct - 实现取消功能"></a>cancelCtx Struct - 实现取消功能</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//包装Context。创建新的 Context </span>
<span class="token keyword">type</span> cancelCtx <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	Context

	mu       sync<span class="token punctuation">.</span>Mutex            <span class="token comment">// 用来保护后面的是那个字段</span>
	done     <span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>         <span class="token comment">// created lazily, closed by first cancel call</span>
	children <span class="token keyword">map</span><span class="token punctuation">[</span>canceler<span class="token punctuation">]</span><span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token comment">// set to nil by the first cancel call</span>
	err      <span class="token builtin">error</span>                 <span class="token comment">// set to non-nil by the first cancel call</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//获取 channel；用来判断是否关闭</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>cancelCtx<span class="token punctuation">)</span> <span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;-</span><span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token punctuation">&#123;</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> c<span class="token punctuation">.</span>done <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		c<span class="token punctuation">.</span>done <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	d <span class="token operator">:=</span> c<span class="token punctuation">.</span>done
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> d
<span class="token punctuation">&#125;</span>

<span class="token comment">//获取关闭原因</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>cancelCtx<span class="token punctuation">)</span> <span class="token function">Err</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	err <span class="token operator">:=</span> c<span class="token punctuation">.</span>err
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span>

<span class="token comment">//</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>cancelCtx<span class="token punctuation">)</span> <span class="token function">Value</span><span class="token punctuation">(</span>key <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> key <span class="token operator">==</span> <span class="token operator">&amp;</span>cancelCtxKey <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> c
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> c<span class="token punctuation">.</span>Context<span class="token punctuation">.</span><span class="token function">Value</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//取消context</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>cancelCtx<span class="token punctuation">)</span> <span class="token function">cancel</span><span class="token punctuation">(</span>removeFromParent <span class="token builtin">bool</span><span class="token punctuation">,</span> err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//如果没有传递取消原因，直接panic</span>
	<span class="token keyword">if</span> err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>  
		<span class="token function">panic</span><span class="token punctuation">(</span><span class="token string">"context: internal error: missing cancel error"</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">//已经存在取消原因，说明已经取消，直接返回</span>
	<span class="token keyword">if</span> c<span class="token punctuation">.</span>err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>  
		c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> <span class="token comment">// already canceled</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//赋值取消原因</span>
	c<span class="token punctuation">.</span>err <span class="token operator">=</span> err  
	<span class="token keyword">if</span> c<span class="token punctuation">.</span>done <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span> <span class="token comment">//如果通道是nil。赋值一个关闭的通道</span>
		c<span class="token punctuation">.</span>done <span class="token operator">=</span> closedchan
	<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span> <span class="token comment">//如果通道不是 nil 。直接关闭当前通道</span>
		<span class="token function">close</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>done<span class="token punctuation">)</span> 
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//遍历子节点，层级关闭</span>
	<span class="token keyword">for</span> child <span class="token operator">:=</span> <span class="token keyword">range</span> c<span class="token punctuation">.</span>children <span class="token punctuation">&#123;</span>
		<span class="token comment">// NOTE: acquiring the child's lock while holding parent's lock.</span>
		child<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	c<span class="token punctuation">.</span>children <span class="token operator">=</span> <span class="token boolean">nil</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	
    <span class="token comment">//解除绑定关系</span>
	<span class="token keyword">if</span> removeFromParent <span class="token punctuation">&#123;</span>
		<span class="token function">removeChild</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>Context<span class="token punctuation">,</span> c<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="timerCtx-取消，定时自动取消"><a href="#timerCtx-取消，定时自动取消" class="headerlink" title="timerCtx - 取消，定时自动取消"></a>timerCtx - 取消，定时自动取消</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 对 cancelCtx 的 再次包装</span>
<span class="token comment">// 在 cancelCtx 的基础上增加了定时器，自动取消功能</span>
<span class="token keyword">type</span> timerCtx <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	cancelCtx
	timer <span class="token operator">*</span>time<span class="token punctuation">.</span>Timer <span class="token comment">// Under cancelCtx.mu.</span>

	deadline time<span class="token punctuation">.</span>Time
<span class="token punctuation">&#125;</span>
<span class="token comment">//返回到期时间</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>timerCtx<span class="token punctuation">)</span> <span class="token function">Deadline</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>deadline time<span class="token punctuation">.</span>Time<span class="token punctuation">,</span> ok <span class="token builtin">bool</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> c<span class="token punctuation">.</span>deadline<span class="token punctuation">,</span> <span class="token boolean">true</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//取消自动取消</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>timerCtx<span class="token punctuation">)</span> <span class="token function">cancel</span><span class="token punctuation">(</span>removeFromParent <span class="token builtin">bool</span><span class="token punctuation">,</span> err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	c<span class="token punctuation">.</span>cancelCtx<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
	<span class="token keyword">if</span> removeFromParent <span class="token punctuation">&#123;</span>
		<span class="token comment">// Remove this timerCtx from its parent cancelCtx's children.</span>
		<span class="token function">removeChild</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>cancelCtx<span class="token punctuation">.</span>Context<span class="token punctuation">,</span> c<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> c<span class="token punctuation">.</span>timer <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		c<span class="token punctuation">.</span>timer<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		c<span class="token punctuation">.</span>timer <span class="token operator">=</span> <span class="token boolean">nil</span>
	<span class="token punctuation">&#125;</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="valueCtx-struct-实现数据存储"><a href="#valueCtx-struct-实现数据存储" class="headerlink" title="valueCtx struct - 实现数据存储"></a>valueCtx <strong>struct - 实现数据存储</strong></h2><pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">//包装 context，实现数据存储</span>
<span class="token keyword">type</span> valueCtx <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
   Context
   key<span class="token punctuation">,</span> val <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//根据 key 获取 value</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>valueCtx<span class="token punctuation">)</span> <span class="token function">Value</span><span class="token punctuation">(</span>key <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> c<span class="token punctuation">.</span>key <span class="token operator">==</span> key <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> c<span class="token punctuation">.</span>val
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> c<span class="token punctuation">.</span>Context<span class="token punctuation">.</span><span class="token function">Value</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="propagateCancel、removeChild-绑定-parent-和-child"><a href="#propagateCancel、removeChild-绑定-parent-和-child" class="headerlink" title="propagateCancel、removeChild - 绑定 parent 和 child"></a>propagateCancel、removeChild - 绑定 parent 和 child</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">// parent 和 child 设置关联关系；一旦 parent 取消。则 child 取消</span>
<span class="token keyword">func</span> <span class="token function">propagateCancel</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">,</span> child canceler<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	done <span class="token operator">:=</span> parent<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment">//父级永远不会被取消，因此不必把 child 和 parent 做关联</span>
    <span class="token comment">//这种情况的parent 一般是 context.Background() OR context.TODO()</span>
	<span class="token keyword">if</span> done <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token comment">// parent is never canceled</span>
	<span class="token punctuation">&#125;</span>

    <span class="token comment">//父级已经被取消，直接取消 child</span>
	<span class="token keyword">select</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">case</span> <span class="token operator">&lt;-</span>done<span class="token punctuation">:</span>
		<span class="token comment">// parent is already canceled</span>
		child<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> parent<span class="token punctuation">.</span><span class="token function">Err</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token keyword">default</span><span class="token punctuation">:</span>
	<span class="token punctuation">&#125;</span>
	
    <span class="token comment">//断言父级，断言是否是 cancelCtx</span>
    <span class="token comment">//	如果是：把 child 放置到 parent 的 children 字段</span>
    <span class="token comment">//  如果不是：开启 goroutine 监控父级done，父级取消，则取消child</span>
	<span class="token keyword">if</span> p<span class="token punctuation">,</span> ok <span class="token operator">:=</span> <span class="token function">parentCancelCtx</span><span class="token punctuation">(</span>parent<span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token punctuation">&#123;</span>
		p<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token keyword">if</span> p<span class="token punctuation">.</span>err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
			<span class="token comment">// parent has already been canceled</span>
			child<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> p<span class="token punctuation">.</span>err<span class="token punctuation">)</span>
		<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">if</span> p<span class="token punctuation">.</span>children <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
				p<span class="token punctuation">.</span>children <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">map</span><span class="token punctuation">[</span>canceler<span class="token punctuation">]</span><span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
			<span class="token punctuation">&#125;</span>
			p<span class="token punctuation">.</span>children<span class="token punctuation">[</span>child<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span>
		p<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
		atomic<span class="token punctuation">.</span><span class="token function">AddInt32</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>goroutines<span class="token punctuation">,</span> <span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span>
		<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">select</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">case</span> <span class="token operator">&lt;-</span>parent<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
				child<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> parent<span class="token punctuation">.</span><span class="token function">Err</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
			<span class="token keyword">case</span> <span class="token operator">&lt;-</span>child<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
			<span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//断言 parent Context 的类型是否是 *cancelCtx</span>
<span class="token keyword">func</span> <span class="token function">parentCancelCtx</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token operator">*</span>cancelCtx<span class="token punctuation">,</span> <span class="token builtin">bool</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	done <span class="token operator">:=</span> parent<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> done <span class="token operator">==</span> closedchan <span class="token operator">||</span> done <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token boolean">nil</span><span class="token punctuation">,</span> <span class="token boolean">false</span>
	<span class="token punctuation">&#125;</span>
	p<span class="token punctuation">,</span> ok <span class="token operator">:=</span> parent<span class="token punctuation">.</span><span class="token function">Value</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>cancelCtxKey<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token operator">*</span>cancelCtx<span class="token punctuation">)</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token boolean">nil</span><span class="token punctuation">,</span> <span class="token boolean">false</span>
	<span class="token punctuation">&#125;</span>
	p<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	ok <span class="token operator">=</span> p<span class="token punctuation">.</span>done <span class="token operator">==</span> done
	p<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token boolean">nil</span><span class="token punctuation">,</span> <span class="token boolean">false</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> p<span class="token punctuation">,</span> <span class="token boolean">true</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// removeChild removes a context from its parent.</span>
<span class="token keyword">func</span> <span class="token function">removeChild</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">,</span> child canceler<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	p<span class="token punctuation">,</span> ok <span class="token operator">:=</span> <span class="token function">parentCancelCtx</span><span class="token punctuation">(</span>parent<span class="token punctuation">)</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">&#125;</span>
	p<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> p<span class="token punctuation">.</span>children <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token function">delete</span><span class="token punctuation">(</span>p<span class="token punctuation">.</span>children<span class="token punctuation">,</span> child<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	p<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="Withcancel、WithDeadline、WithTimeout、WithValue"><a href="#Withcancel、WithDeadline、WithTimeout、WithValue" class="headerlink" title="Withcancel、WithDeadline、WithTimeout、WithValue"></a>Withcancel、WithDeadline、WithTimeout、WithValue</h2><pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">// cancelCtx struct 包一下Context，然后返回</span>
<span class="token keyword">func</span> <span class="token function">WithCancel</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">)</span> <span class="token punctuation">(</span>ctx Context<span class="token punctuation">,</span> cancel CancelFunc<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	c <span class="token operator">:=</span> <span class="token function">newCancelCtx</span><span class="token punctuation">(</span>parent<span class="token punctuation">)</span>
	<span class="token function">propagateCancel</span><span class="token punctuation">(</span>parent<span class="token punctuation">,</span> <span class="token operator">&amp;</span>c<span class="token punctuation">)</span>
	<span class="token keyword">return</span> <span class="token operator">&amp;</span>c<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> c<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">,</span> Canceled<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 在 cancelCtx 的基础上，支持定时自动取消功能</span>
<span class="token keyword">func</span> <span class="token function">WithDeadline</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">,</span> d time<span class="token punctuation">.</span>Time<span class="token punctuation">)</span> <span class="token punctuation">(</span>Context<span class="token punctuation">,</span> CancelFunc<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> cur<span class="token punctuation">,</span> ok <span class="token operator">:=</span> parent<span class="token punctuation">.</span><span class="token function">Deadline</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> ok <span class="token operator">&amp;&amp;</span> cur<span class="token punctuation">.</span><span class="token function">Before</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token comment">// The current deadline is already sooner than the new one.</span>
		<span class="token keyword">return</span> <span class="token function">WithCancel</span><span class="token punctuation">(</span>parent<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	c <span class="token operator">:=</span> <span class="token operator">&amp;</span>timerCtx<span class="token punctuation">&#123;</span>
		cancelCtx<span class="token punctuation">:</span> <span class="token function">newCancelCtx</span><span class="token punctuation">(</span>parent<span class="token punctuation">)</span><span class="token punctuation">,</span>
		deadline<span class="token punctuation">:</span>  d<span class="token punctuation">,</span>
	<span class="token punctuation">&#125;</span>
	<span class="token function">propagateCancel</span><span class="token punctuation">(</span>parent<span class="token punctuation">,</span> c<span class="token punctuation">)</span>
	dur <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Until</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span>
	<span class="token keyword">if</span> dur <span class="token operator">&lt;=</span> <span class="token number">0</span> <span class="token punctuation">&#123;</span>
		c<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">,</span> DeadlineExceeded<span class="token punctuation">)</span> <span class="token comment">// deadline has already passed</span>
		<span class="token keyword">return</span> c<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> c<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> Canceled<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span>
	c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> c<span class="token punctuation">.</span>mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> c<span class="token punctuation">.</span>err <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		c<span class="token punctuation">.</span>timer <span class="token operator">=</span> time<span class="token punctuation">.</span><span class="token function">AfterFunc</span><span class="token punctuation">(</span>dur<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			c<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">,</span> DeadlineExceeded<span class="token punctuation">)</span>
		<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> c<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> c<span class="token punctuation">.</span><span class="token function">cancel</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">,</span> Canceled<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 定时取消的变一种形式，传递的不再是到期时间，而是相对当前时间的时间间隔</span>
<span class="token keyword">func</span> <span class="token function">WithTimeout</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">,</span> timeout time<span class="token punctuation">.</span>Duration<span class="token punctuation">)</span> <span class="token punctuation">(</span>Context<span class="token punctuation">,</span> CancelFunc<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token function">WithDeadline</span><span class="token punctuation">(</span>parent<span class="token punctuation">,</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>timeout<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 在 context 存储数据</span>
<span class="token keyword">func</span> <span class="token function">WithValue</span><span class="token punctuation">(</span>parent Context<span class="token punctuation">,</span> key<span class="token punctuation">,</span> val <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> Context <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> key <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		<span class="token function">panic</span><span class="token punctuation">(</span><span class="token string">"nil key"</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>reflectlite<span class="token punctuation">.</span><span class="token function">TypeOf</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Comparable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token function">panic</span><span class="token punctuation">(</span><span class="token string">"key is not comparable"</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> <span class="token operator">&amp;</span>valueCtx<span class="token punctuation">&#123;</span>parent<span class="token punctuation">,</span> key<span class="token punctuation">,</span> val<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>基于 cancelCtx、timerCtx、valueCtx 三中 struct 以及对应的方法。实现了 批量、定时发送取消信号、数据存储的功能。其中 核心方法包括</p>
<ul>
<li>cancel() 用于发送取消信号（通过关闭通道 close(c.done) 发送）</li>
<li>propagateCancel() 关联 parent 和 child。做到一旦 parent cancel 则 child cancel</li>
<li>WithValue() 通过key获取存储的value</li>
</ul>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">he7009</p>
  <div class="site-description" itemprop="description">Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">9</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">he7009</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
